var data = {
	origin : [],
	let : [],
	trip : [],
	proAct : [],
	fake : [],
	xData : []
};
var linechart;
// 根据动作时间造点，前0后1
function initActDataByActTime(actTime) {
	var pointSet = [];
	if (actTime == 0) {
		// 如果没有取到时间，就画一条直线
		var changePoint = 1001;
	} else {
		var changePoint = actTime / 200;
	}
	for (var i = -100; i < 1000; i++) {
		if (i >= changePoint) {
			pointSet.push([ (i * 0.2).toFixed(2), 1 ]);
		} else {
			pointSet.push([ (i * 0.2).toFixed(2), 0 ]);
		}

	}
	return pointSet;
}
function getWaveData(fileId, breakerId, phase, actTime, removeTime, protectAct,xhTimeInterval,exceptionType,cross0Time,actionTimeInterval) {
	data.origin = [];
	data.let = [];
	if (data.xData.length == 0) {
		initActDataByActTime();
	}
	;
	var actPoint = Math.floor((Number(actTime) / 200)) + 1;
	var removePoint = Math.floor((Number(removeTime) / 200)) + 1;// 从数据库中取到的点
	var protectActPoint = Math.floor((Number(protectAct) / 200)) + 1;//保护动作时间
	$.getJSON('/rest/waveData/getBreakerWaveLetData/' + fileId + "/"
			+ breakerId + "/" + phase, function(result) {
		// {"preFault":[[],[]],"postFault":[[],[]]}
		// for ( var i in result) {
		// drawChart("chart" + i, result[i]);
		// }

		// 小波突变点后找故障切除点
		/*
		 * var originRemoveDataList = [];// 从小波突变点后30个点找故障切除点 for (var i =
		 * maxLet - 1; i < maxLet + 99; i++) {
		 * originRemoveDataList.push(result["postFault"][0][i]); } var
		 * faultRemovePoint = getFaultRemovePoint(maxLet, originRemoveDataList);
		 */
		if (!$.isEmptyObject(result)) {
			// 从数据库中取到的切除点，往前开始找故障切除点
			var finalRemovePoint = getRemovePoint(result["postFault"][0],
					result["postFault"][6], removePoint);

			// 小波熄弧点(从保护发跳点到最终故障切除点前10个点找小波最大值)
			//改为直接从数据库中取熄弧时间，不再自己计算
//			var maxLet = getMaxLet(result["postFault"][6], finalRemovePoint,
//					protectActPoint);// 获取小波突变点
			//
			//var maxLet=Math.floor((Number(xhTime) / 200)) + 1;
			var rtn = initBreakerWaveData(result);
			for (var i = 0; i < rtn[0].length; i++) {
				data.origin.push([ ((i - 100) * 0.2).toFixed(2), rtn[0][i] ]);
			}
			for (var i = 0; i < rtn[6].length; i++) {
				data.let.push([ ((i - 100) * 0.2).toFixed(2), rtn[6][i] ]);
			}
			var finalRemoveTime=(finalRemovePoint * 0.2).toFixed(2);
			//如果标题是:故障电流过零异常
			if(exceptionType == 'gzdlgldyc'){
				var xhTime = cross0Time/1000;
			}else if(exceptionType == 'dlqyc'){
				var xhTime = (protectActPoint-2)*0.2;
			       finalRemoveTime = xhTime+(actionTimeInterval/1000);
			}else{
				var xhTime=finalRemoveTime-xhTimeInterval/1000;
			}
			// 画图
			drawChart(xhTime, (actPoint * 0.2).toFixed(2),
					finalRemoveTime, (removePoint * 0.2)
							.toFixed(2));
		}
	});
}
// 从removePoint往前后找变号的点，（后面如果有过零点优先级比前面的要高）然后往后找小波最大的点
function getRemovePoint(originData, letDataSet, removePoint) {
	var removeCurrent = originData[removePoint];
	var endCalcPoint = removePoint;
	var glPoint = 0;// 过零点
	// 1.从故障切除点开始往后15个点找过零点，如果没有找到就再往前15个点找过零点
	if (removeCurrent > 0) {
		// 如果大于零，就找第一个负值
		// 先向后找
		for (var i = removePoint; i <= removePoint + 15; i++) {
			if (i > 0 && originData[i] < 0) {
				glPoint = i;
				break;
			}
			if (i == endCalcPoint + 15) {
				// 如果后面没有过零点，向前找
				for (var j = endCalcPoint; j >= endCalcPoint - 15; j--) {
					if (j > 0 && originData[j] < 0) {
						glPoint = j;
						break;
					}
				}
			}
		}
	} else {
		// 如果小于零，就找第一个正值
		for (var i = removePoint; i <= removePoint + 15; i++) {
			if (i > 0 && originData[i] > 0) {
				glPoint = i;
				break;
			}
			if (i == endCalcPoint + 15) {
				// 向前找
				for (var j = endCalcPoint; j >= endCalcPoint - 15; j--) {
					if (j > 0 && originData[j] > 0) {
						glPoint = j;
						break;
					}
				}
			}
		}
	}
	// 2.在过零点和切除点之间找小波最大值
	// 如果过零点在切除点之前，从过零点之后找最大值,如果在切除点之后从过零点之前找
	var maxValue = 0;// 小波最大数值
	var maxValuePos = endCalcPoint;// 小波最大值所在位置，初始为故障切除点
	if (glPoint < removePoint && glPoint > 0) {
		// 过零点在切除点之前
		for (var i = glPoint; i <= endCalcPoint; i++) {
			if (Math.abs(letDataSet[i]) > maxValue) {
				maxValue = Math.abs(letDataSet[i]);
				maxValuePos = i;
			}
		}
	} else if (glPoint > removePoint && glPoint > 0) {
		// 过零点在切除点之后
		for (var i = endCalcPoint; i <= glPoint; i++) {
			if (Math.abs(letDataSet[i]) > maxValue) {
				maxValue = Math.abs(letDataSet[i]);
				maxValuePos = i;
			}
		}
	} else if (glPoint == 0) {
		// 没有过零点
		for (var i = endCalcPoint - 15; i <= endCalcPoint + 15; i++) {
			if (Math.abs(letDataSet[i]) > maxValue) {
				maxValue = Math.abs(letDataSet[i]);
				maxValuePos = i;
			}
		}

	}
	// 3.判断小波最大值所在的位置，原始波形值是否小于0.2kA
	while (Math.abs(originData[maxValuePos]) > 0.3) {
		// 如果原始值大于0.2kA,就找下一个小波最大值
		maxValue = 0;
		if (maxValuePos < removePoint) {
			// 如果小波最大值所在位置在切除点之前
			for (var i = maxValuePos + 1; i <= removePoint; i++) {
				if (Math.abs(letDataSet[i]) > maxValue) {
					maxValue = Math.abs(letDataSet[i]);
					maxValuePos = i;
				}
			}
		} else if (maxValuePos > removePoint) {
			// 如果小波最大值所在位置在切除点之后
			for (var i = removePoint; i <= maxValuePos - 1; i++) {
				if (i > 0 && Math.abs(letDataSet[i]) > maxValue) {
					maxValue = Math.abs(letDataSet[i]);
					maxValuePos = i;
				}
			}
		} else {
			maxValuePos = removePoint;
			break;
		}
	}
	// 4.看前面点的原始波形值是不是小于0.3,直到找到大于0.3的点
	while (Math.abs(originData[maxValuePos - 1]) < 0.3) {
		maxValuePos--;
	}
	return maxValuePos;
}
// 将故障前后数据组织在一起,故障前取100个点
function initBreakerWaveData(dataSet) {
	var dataList = [];
	for ( var i in dataSet["preFault"]) {
		var datas = [];
		for (var j = 200; j <= 299; j++) {
			datas.push(dataSet["preFault"][i][j]);
		}
		for ( var k in dataSet["postFault"][i]) {
			datas.push(dataSet["postFault"][i][k]);
		}
		dataList.push(datas);
	}
	return dataList;
}
// 找小波熄弧点
function getMaxLet(dataSet, finalRemovePoint, protectActPoint) {
	var max = 0;
	var maxPosition = 0;
	for (var i = protectActPoint; i <= finalRemovePoint - 10; i++) {
		if (Math.abs(dataSet[i]) > max) {
			max = Math.abs(dataSet[i]);
			maxPosition = i;
		}
	}
	return maxPosition;
}
// 按照斜率找故障切除点
function getFaultRemovePoint(startPoint, dataList) {
	var changeRate = 0;
	var position = 0;
	for (var i = 1; i < dataList.length - 1; i++) {
		var changeRate1 = (Math.abs(dataList[i]) >= Math.abs(dataList[i - 1])) ? Math
				.abs(dataList[i] / dataList[i - 1])
				: Math.abs(dataList[i - 1] / dataList[i]);
		var changeRate2 = (Math.abs(dataList[i]) >= Math.abs(dataList[i + 1])) ? Math
				.abs(dataList[i] / dataList[i + 1])
				: Math.abs(dataList[i + 1] / dataList[i]);
		var changeProperty = (changeRate1 >= changeRate2) ? (changeRate1 / changeRate2)
				: (changeRate2 / changeRate1);
		if (changeRate <= changeProperty) {
			changeRate = changeProperty;
			position = (changeRate1 > changeRate2) ? i : i + 1;
		}
	}
	return startPoint + position - 1;
}
function drawChart(maxLet, actPoint, faultRemovePoint, removePoint) {
	linechart = echarts.init(document.getElementById("wave"));
	var baseTop = 70;
	var gridHeight = 100;
	function makeXAxis(gridIndex, opt) {
		return echarts.util.merge({
			type : 'value',
			data : data.xData,
			gridIndex : gridIndex,
			axisLine : {
				onZero : false,
				lineStyle : {
					color : '#ddd'
				}
			},
			axisTick : {
				show : false
			},
			axisLabel : {
				show : false
			},
			splitLine : {
				show : false,
				lineStyle : {
					color : '#ddd'
				}
			},
			axisPointer : {
				lineStyle : {
					color : 'transparent'
				}
			}
		}, opt || {}, true);
	}

	function makeYAxis(gridIndex, opt) {
		return echarts.util.merge({
			type : 'value',
			gridIndex : gridIndex,
			nameLocation : 'middle',
			nameTextStyle : {
				color : '#333'
			},
			boundaryGap : [ '30%', '30%' ],
			axisTick : {
				show : false
			},
			axisLine : {
				lineStyle : {
					color : '#ccc'
				}
			},
			axisLabel : {
				show : false
			},
			splitLine : {
				show : false
			}
		}, opt || {}, true);
	}

	function makeGrid(top, opt) {
		return echarts.util.merge({
			left : '3%',
			right : "3%",
			top : top,
			height : gridHeight
		}, opt || {}, true);
	}

	option = {
		tooltip : {
			trigger : 'axis',
			backgroundColor : '#fff',
			borderColor : 'rgba(0, 0, 200, 0.2)',
			borderWidth : 1,
			borderRadius : 0,
			padding : 10,
			formatter : function(params) {
				/*
				 * return '<span style="color:black">' + params[0].value[0] +
				 * 'ms</span>';
				 */

				// 可以显示各波形值
				if (params.length) {
					params.unshift({
						seriesName : '时间',
						value : [ null, params[0].value[0] + ' ms' ],
						color : '#5193f2'
					})
					return echarts.util.map(
							[ '时间', '原始' ],
							function(seriesName) {
								for (var i = 0; i < params.length - 1; i++) {
									var param = params[i];
									var style = 'color: ' + param.color;
									if (param.seriesName === seriesName) {
										if (seriesName == '原始'
												&& (param.value[1] + "")
														.indexOf("kA") == -1) {
											param.value[1] += 'kA';
										}
										return '<span style="' + style + '">'
												+ param.seriesName
												+ '：</span><span style="'
												+ style + '">' + param.value[1]
												+ '</span>';
									}
								}
							}).join('<br/>');
				}

			}
		},
		axisPointer : {
			link : [ {
				xAxisIndex : 'all'
			} ],
			snap : true
		},
		grid : [ makeGrid(baseTop), makeGrid(baseTop + gridHeight),
				makeGrid(baseTop + gridHeight * 2),
				makeGrid(baseTop + gridHeight * 3), makeGrid(baseTop, {
					show : true,
					height : gridHeight * 4,
					borderColor : '#ccc',
					borderWidth : 1,
					z : 10
				}) ],
		xAxis : [ makeXAxis(0), makeXAxis(1), makeXAxis(2), makeXAxis(3),
				makeXAxis(4, {
					position : 'bottom',
					axisLine : {
						show : false,
						onZero : false
					},
					splitLine : {
						show : true
					},
					axisLabel : {
						show : true,
						textStyle : {
							color : '#555'
						}
					},
					axisPointer : {
						show : true,
						lineStyle : {
							color : '#478cf1',
							width : 1.5
						}
					}
				}) ],
		yAxis : [ makeYAxis(0, {
			name : '原始'
		}), makeYAxis(1, {
			name : '小波'
		}), makeYAxis(2, {
			name : '跳位'
		}), makeYAxis(3, {
			name : '保护'
		}), makeYAxis(4) ],
		dataZoom : [ {
			type : 'slider',
			top : baseTop + gridHeight * 4 + 40,
			xAxisIndex : [ 0, 1, 2, 3, 4 ],
			startValue : -20,
			endValue : 100
		}, {
			type : 'inside',
			xAxisIndex : [ 0, 1, 2, 3, 4 ]
		} ],
		series : [ {
			name : '原始',
			type : 'line',
			symbol : 'circle',
			smooth : true,
			symbolSize : 2,
			itemStyle : {
				normal : {
					color : '#5193f2'
				}
			},
			data : data.origin
		}, {
			name : '小波',
			type : 'line',
			symbol : 'circle',
			smooth : true,
			symbolSize : 2,
			xAxisIndex : 1,
			yAxisIndex : 1,
			itemStyle : {
				normal : {
					color : '#75b228'
				}
			},
			data : data.let
		}, {
			name : '跳位',
			type : 'line',
			symbol : 'circle',
			smooth : true,
			symbolSize : 2,
			xAxisIndex : 2,
			yAxisIndex : 2,
			itemStyle : {
				normal : {
					color : '#e29304'
				}
			},
			data : data.trip
		}, {
			name : '保护',
			type : 'line',
			symbol : 'circle',
			smooth : true,
			symbolSize : 2,
			xAxisIndex : 3,
			yAxisIndex : 3,
			itemStyle : {
				normal : {
					color : '#9932CC'
				} 
			},
			data : data.proAct
		}, {
			name : 'main',
			type : 'line',
			symbol : 'none',
			symbolSize : 2,
			itemStyle : {
				normal : {
					color : 'transparent'
				}
			},
			markLine : {
				lineStyle : {
					normal : {
						type : 'solid',
						color : 'red'
					}
				},
				data : [ {
					xAxis : '0.00'
				}
				/*
				 * , { xAxis : removePoint, lineStyle:{ normal:{color:'blue'} } }
				 */
				, {
					xAxis : maxLet
				}

				, {
					xAxis : faultRemovePoint
				}

				]
			},
			xAxisIndex : 4,
			yAxisIndex : 4,
			data : data.fake
		} ]
	};
	linechart.setOption(option);
}
function resizeHtml() {
	if (linechart) {
		linechart.resize();
	}
}
